package com.alxy.day1.service.impl;

import com.alxy.day1.entity.Product;
import com.alxy.day1.repository.ProductRepository;
import com.alxy.day1.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 爱莉希雅
 * @version java 17
 */
@SuppressWarnings({"all"})
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductRepository productRepository;
    // 乐观锁购买商品
    private static final int MAX_RETRIES = 3;

    @Transactional
    public boolean purchaseProductOptimistically(Long productId, int quantity) {
        int retries = 0;
        //重试
        while (retries < MAX_RETRIES) {
            Product product = productRepository.findById(productId).orElse(null);
            if (product != null && product.getStock() >= quantity) {
                int rowsAffected = productRepository.updateStockOptimistically(productId, quantity, product.getVersion());
                if (rowsAffected > 0) {
                    return true;
                }
            }
            retries++;
        }
        return false;
    }

    // 悲观锁购买商品
    @Transactional
    public boolean purchaseProductPessimistically(Long productId, int quantity) {
        Product product = productRepository.findByIdWithPessimisticLock(productId);
        //悲观先判断不够不存在
        if (product != null && product.getStock() >= quantity) {
            product.setStock(product.getStock() - quantity);
            productRepository.save(product);
            return true;
        }
        return false;
    }
}
